
<script src="util.js"></script>
<script src="Database.js"></script>
<script>

var Village = {};
var Background = {};
var XHR = {}


XHR.lastDownload = 0;
XHR.timeoutId = null;
XHR.parser = new DOMParser();

XHR.getPage = function (suffix, params, callback) {
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		 if (xhr.readyState == 4) {
			//xml = XHR.parser.parseFromString(xhr.responseText, "text/xml");
			xml = toDOM(xhr.responseText);
		 	callback(xhr.status, xml);
		 }
	}
	xhr.open("GET", "http://s3.travian.co.il/"+suffix, true);
	
	var sendRequest = function() {
		var now = new Date().getTime();
		if (now-XHR.lastDownload > 5000) {
			xhr.send();
			XHR.lastDownload = now;
		} else {
			XHR.timeoutId = setTimeout(sendRequest, 1000);
		}
	}
	
	sendRequest();

}


function VillageManager(villageId) {
	this.villageId = villageId;
	
}

VillageManager.prototype.navigateToVillage = function(onFinished) {
	XHR.getPage('dorf1.php?newdid='+this.villageId, null, onFinished);
}

VillageManager.prototype.runBQ = function(onFinished) {	
	DB.BuildingQueue.top(this.villageId, function(row) {
		var villageId = row.villageId;
		var slotId = row.slotId;
		var level = row.level;
		console.log("Upgrading slot "+slotId+" in village "+villageId);
		XHR.getPage('build.php?id='+slotId, null, function(status, page) {
		console.log(page);
		var n = XPath.getNode('.//p[@id="contract"]//a[@class="build"]', page);
		
		console.log(n);
		if (n == null) {
			onFinished();
			return;
		}
		var link = XPath.getString('./@href', n);
		console.log("upgrade link: "+link);
		XHR.getPage(link, null, function (status, page) {
			
		DB.BuildingQueue.remove(villageId, slotId, level);
		onFinished();
		
		});
		});
	});
}

VillageManager.prototype.runStrategies = function (onFinished) {
	//alert('procesing village '+this.villageId);
	var runBQ = (function(that, onFinished) {
		return function() {
			that.runBQ(onFinished);
		};
	})(this, onFinished);
	
	this.navigateToVillage(function () {
	runBQ();
	});
	
}



function toDOM(HTMLstring)
{
	var d = document.createElement('div');
	d.innerHTML = HTMLstring;
	/*
	var docFrag = document.createDocumentFragment();

	while (d.firstChild) {
	docFrag.appendChild(d.firstChild)
	};
	
	return docFrag;
	*/
	return d;
}




Background.run = function() {
	DB.getAllVillages(function (villagesIds) {
		var i=0;
		var f = function() {
			if (i < villagesIds.length) {
				var v = new VillageManager(villagesIds[i++].villageId);
				v.runStrategies(f);
			}
		}
		f();
	});
	
	
}

Background.isOnline = false;
Background.togglePlayPause = function() {

	var changeIcon = function (iconName) {
		chrome.tabs.getAllInWindow(null, function(tabs) {
			for (var i=0; i < tabs.length; ++i) {
				if (/\.travian\./.test(tabs[i].url)) {
					var img = new Object();
					img.path = chrome.extension.getURL(iconName);
					img.tabId = tabs[i].id;
					chrome.pageAction.setIcon(img);
				}
			}
		});
	}

	if (Background.isOnline) {
		changeIcon('icon48_offline.png');
		Background.pause();
	} else {
		changeIcon('icon48_online.png');
		Background.play();
	}
}

Background.play = function () {
	Background.isOnline = true;
	Background.run();
	Background.timeoutId = setTimeout(Background.play, 10*60*1000);
}

Background.pause = function () {
	Background.isOnline = false;
	if (Background.timeoutId != null) {
		clearTimeout(Background.timeoutId);
		Background.timeoutId = null;
	}
	if (XHR.timeoutId != null) {
		clearTimeout(XHR.timeoutId);
	}
}



function tst () {
	alert('test !');
}

function init() {
	DB.init();
	
	// show icon in address bar
	chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
		if (/\.travian\./.test(tab.url)) {
			var img = new Object();
			if (Background.isOnline) {
				img.path = chrome.extension.getURL('icon48_online.png');
			} else {
				img.path = chrome.extension.getURL('icon48_offline.png');
			}
			img.tabId = tab.id;
			chrome.pageAction.setIcon(img);
			chrome.pageAction.show(tabId);
		}
	});
	
	chrome.pageAction.onClicked.addListener(function (tab) {
		Background.togglePlayPause();
	});
	//Background.play();

	Comm.register('DB.BuildingQueue.enqueue', DB.BuildingQueue.enqueue);
	Comm.register('DB.BuildingQueue.publish', DB.BuildingQueue.publish);
	Comm.register('DB.BuildingQueue.remove',  DB.BuildingQueue.remove);
	Comm.register('tst', tst);
}

init();

</script>
